package net.uman.framework.servlets;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Generates, displays, and stores in session a 200x50 CAPTCHA image with sheared black text, 
 * a solid dark grey background, and a straight, slanted red line through the text.
 */
public class CaptchaServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
		Random random = new Random(new Date().getTime());
		int index = random.nextInt(99);
		
		InputStream is = getClass().getResourceAsStream("/captcha.zip");
		ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
		ZipEntry entry = null;
		for (int i = 0 ; i <= index ; i++) {
			entry = zis.getNextEntry();
		}

		String name = entry.getName();
		name = name.substring(0, name.length() - 4);
		req.getSession().setAttribute("CAPTCHA", name);
		
		OutputStream output = resp.getOutputStream();   
		int count;
		byte data[] = new byte[1024];
		while ((count = zis.read(data, 0, data.length)) != -1) {
			output.write(data, 0, count);
		}
		output.flush();
		output.close();
		zis.close();
    }
}
